/**
 * 销售机会表单页面交互逻辑
 * 实现多步骤表单和完整的数据验证
 */

class OpportunityForm {
    constructor() {
        this.currentStep = 1;
        this.totalSteps = 4;
        this.formData = {};
        this.validationRules = {};
        this.isEditing = false;
        this.opportunityId = null;
        
        this.init();
    }

    init() {
        this.checkEditMode();
        this.initializeValidation();
        this.bindEvents();
        this.initializeComponents();
        this.updateStepDisplay();
    }

    checkEditMode() {
        const urlParams = new URLSearchParams(window.location.search);
        this.opportunityId = urlParams.get('id');
        this.isEditing = !!this.opportunityId;
        
        if (this.isEditing) {
            this.loadExistingData();
            document.querySelector('.page-title').textContent = '编辑销售机会';
            document.getElementById('save-opportunity-btn').innerHTML = 
                '<i class="fas fa-save"></i> 保存修改';
        }
    }

    loadExistingData() {
        // 模拟加载现有数据
        setTimeout(() => {
            this.populateFormWithExistingData();
        }, 300);
    }

    populateFormWithExistingData() {
        // 模拟数据填充
        const mockData = {
            opportunityName: '李女士夫妇-云南深度7日游',
            opportunityLevel: 'A',
            leadSource: 'activity',
            opportunityType: 'repeat-customer',
            consultant: '1',
            expectedAmount: '15800',
            expectedCloseDate: '2025-01-25',
            expectedDepartureDate: '2025-02-10'
        };
        
        Object.keys(mockData).forEach(key => {
            const element = document.getElementById(key.replace(/([A-Z])/g, '-$1').toLowerCase());
            if (element) {
                element.value = mockData[key];
            }
        });
    }

    // ==================== 验证规则初始化 ====================
    initializeValidation() {
        this.validationRules = {
            step1: {
                'opportunity-name': { required: true, minLength: 2 },
                'opportunity-level': { required: true },
                'lead-source': { required: true },
                'opportunity-type': { required: true },
                'consultant': { required: true },
                'expected-amount': { required: true, min: 0 },
                'expected-close-date': { required: true }
            },
            step2: {
                // 步骤2的字段都是可选的，但可以添加特定验证
            },
            step3: {
                // 步骤3的字段都是可选的
            },
            step4: {
                'first-followup-time': { required: true },
                'first-followup-method': { required: true },
                'followup-goal': { required: true }
            }
        };
    }

    // ==================== 事件绑定 ====================
    bindEvents() {
        this.bindStepNavigation();
        this.bindFormInputs();
        this.bindCustomerSelection();
        this.bindSpecialComponents();
        this.bindFormSubmission();
    }

    bindStepNavigation() {
        // 步骤指示器点击
        document.querySelectorAll('.step').forEach((step, index) => {
            step.addEventListener('click', () => {
                const stepNumber = index + 1;
                if (stepNumber <= this.currentStep || this.isStepCompleted(stepNumber - 1)) {
                    this.goToStep(stepNumber);
                }
            });
        });
        
        // 上一步按钮
        document.getElementById('prev-step-btn')?.addEventListener('click', () => {
            this.previousStep();
        });
        
        // 下一步按钮
        document.getElementById('next-step-btn')?.addEventListener('click', () => {
            this.nextStep();
        });
    }

    bindFormInputs() {
        // 实时验证
        document.addEventListener('input', (e) => {
            if (e.target.matches('input, select, textarea')) {
                this.validateField(e.target);
            }
        });
        
        // 失焦验证
        document.addEventListener('blur', (e) => {
            if (e.target.matches('input, select, textarea')) {
                this.validateField(e.target);
            }
        }, true);
    }

    bindCustomerSelection() {
        // 客户搜索
        document.getElementById('customer-search')?.addEventListener('input', (e) => {
            this.searchCustomers(e.target.value);
        });
        
        // 选择客户按钮
        document.getElementById('select-customer-btn')?.addEventListener('click', () => {
            this.showCustomerSelector();
        });
        
        // 客户选择器中的搜索
        document.getElementById('customer-search-input')?.addEventListener('input', (e) => {
            this.filterCustomerList(e.target.value);
        });
        
        // 客户选择
        this.bindCustomerSelectEvents();
    }

    bindCustomerSelectEvents() {
        document.addEventListener('click', (e) => {
            if (e.target.closest('.select-customer-btn')) {
                const customerItem = e.target.closest('.customer-item');
                const customerId = customerItem.dataset.customerId;
                this.selectCustomer(customerId);
            }
        });
    }

    bindSpecialComponents() {
        // 决策因素评估滑块
        document.querySelectorAll('.factor-range').forEach(range => {
            range.addEventListener('input', (e) => {
                this.updateRatingValue(e.target);
            });
        });
        
        // 竞争对手信息显示/隐藏
        document.querySelectorAll('input[name="has-competitor"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                this.toggleCompetitorDetails(e.target.value === 'yes');
            });
        });
        
        // 需求标签选择
        document.querySelectorAll('.tag-checkbox input').forEach(checkbox => {
            checkbox.addEventListener('change', () => {
                this.updateRequirementTags();
            });
        });
    }

    bindFormSubmission() {
        // 表单提交
        document.getElementById('opportunity-form')?.addEventListener('submit', (e) => {
            e.preventDefault();
            this.submitForm();
        });
        
        // 保存草稿
        document.getElementById('save-draft-btn')?.addEventListener('click', () => {
            this.saveDraft();
        });
        
        // 创建/保存按钮
        document.getElementById('save-opportunity-btn')?.addEventListener('click', () => {
            this.submitForm();
        });
    }

    // ==================== 步骤导航 ====================
    goToStep(stepNumber) {
        if (stepNumber < 1 || stepNumber > this.totalSteps) return;
        
        // 验证当前步骤（如果是前进）
        if (stepNumber > this.currentStep && !this.validateCurrentStep()) {
            return;
        }
        
        // 隐藏当前步骤
        document.getElementById(`step-${this.currentStep}`)?.classList.remove('active');
        
        // 显示目标步骤
        this.currentStep = stepNumber;
        document.getElementById(`step-${this.currentStep}`)?.classList.add('active');
        
        this.updateStepDisplay();
        this.updateNavigationButtons();
        
        // 滚动到顶部
        document.querySelector('.form-container').scrollIntoView({ 
            behavior: 'smooth' 
        });
    }

    nextStep() {
        if (this.currentStep < this.totalSteps) {
            this.goToStep(this.currentStep + 1);
        } else {
            this.submitForm();
        }
    }

    previousStep() {
        if (this.currentStep > 1) {
            this.goToStep(this.currentStep - 1);
        }
    }

    updateStepDisplay() {
        // 更新步骤指示器
        document.querySelectorAll('.step').forEach((step, index) => {
            const stepNumber = index + 1;
            
            step.classList.remove('active', 'completed');
            
            if (stepNumber === this.currentStep) {
                step.classList.add('active');
            } else if (stepNumber < this.currentStep) {
                step.classList.add('completed');
            }
        });
    }

    updateNavigationButtons() {
        const prevBtn = document.getElementById('prev-step-btn');
        const nextBtn = document.getElementById('next-step-btn');
        const submitBtn = document.getElementById('submit-btn');
        
        // 上一步按钮
        if (prevBtn) {
            prevBtn.style.display = this.currentStep > 1 ? 'inline-flex' : 'none';
        }
        
        // 下一步/提交按钮
        if (this.currentStep === this.totalSteps) {
            nextBtn.style.display = 'none';
            submitBtn.style.display = 'inline-flex';
        } else {
            nextBtn.style.display = 'inline-flex';
            submitBtn.style.display = 'none';
        }
    }

    // ==================== 表单验证 ====================
    validateCurrentStep() {
        const stepRules = this.validationRules[`step${this.currentStep}`];
        if (!stepRules) return true;
        
        let isValid = true;
        const errors = [];
        
        Object.keys(stepRules).forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field && !this.validateField(field, stepRules[fieldId])) {
                isValid = false;
                errors.push(this.getFieldLabel(fieldId));
            }
        });
        
        if (!isValid) {
            this.showValidationErrors(errors);
        }
        
        return isValid;
    }

    validateField(field, rules = null) {
        if (!rules) {
            const stepRules = this.validationRules[`step${this.currentStep}`];
            rules = stepRules?.[field.id];
        }
        
        if (!rules) return true;
        
        const value = field.value.trim();
        let isValid = true;
        let errorMessage = '';
        
        // 必填验证
        if (rules.required && !value) {
            isValid = false;
            errorMessage = '此字段为必填项';
        }
        
        // 最小长度验证
        if (isValid && rules.minLength && value.length < rules.minLength) {
            isValid = false;
            errorMessage = `最少需要${rules.minLength}个字符`;
        }
        
        // 最小值验证
        if (isValid && rules.min !== undefined && parseFloat(value) < rules.min) {
            isValid = false;
            errorMessage = `值不能小于${rules.min}`;
        }
        
        // 邮箱验证
        if (isValid && rules.email && !this.isValidEmail(value)) {
            isValid = false;
            errorMessage = '请输入有效的邮箱地址';
        }
        
        // 手机号验证
        if (isValid && rules.phone && !this.isValidPhone(value)) {
            isValid = false;
            errorMessage = '请输入有效的手机号';
        }
        
        this.showFieldValidation(field, isValid, errorMessage);
        return isValid;
    }

    showFieldValidation(field, isValid, errorMessage) {
        // 移除之前的验证状态
        field.classList.remove('field-valid', 'field-invalid');
        
        // 移除之前的错误消息
        const existingError = field.parentNode.querySelector('.field-error');
        if (existingError) {
            existingError.remove();
        }
        
        if (!isValid) {
            field.classList.add('field-invalid');
            
            // 添加错误消息
            const errorDiv = document.createElement('div');
            errorDiv.className = 'field-error';
            errorDiv.textContent = errorMessage;
            errorDiv.style.cssText = `
                color: #ff3b30;
                font-size: 12px;
                margin-top: 4px;
            `;
            
            field.parentNode.appendChild(errorDiv);
        } else if (field.value.trim()) {
            field.classList.add('field-valid');
        }
    }

    showValidationErrors(errors) {
        const message = '请完善以下必填信息：\n' + errors.join('\n');
        this.showNotification(message, 'error');
    }

    getFieldLabel(fieldId) {
        const field = document.getElementById(fieldId);
        const label = field?.closest('.form-group')?.querySelector('.form-label');
        return label?.textContent.replace('*', '').trim() || fieldId;
    }

    isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    isValidPhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone.replace(/\D/g, ''));
    }

    isStepCompleted(stepNumber) {
        // 检查步骤是否已完成
        const stepRules = this.validationRules[`step${stepNumber}`];
        if (!stepRules) return true;
        
        return Object.keys(stepRules).every(fieldId => {
            const field = document.getElementById(fieldId);
            return field && this.validateField(field, stepRules[fieldId]);
        });
    }

    // ==================== 客户选择 ====================
    showCustomerSelector() {
        const modal = document.getElementById('customer-selector-modal');
        if (modal) {
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
            
            // 重置搜索
            document.getElementById('customer-search-input').value = '';
            this.filterCustomerList('');
        }
    }

    closeCustomerSelector() {
        const modal = document.getElementById('customer-selector-modal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }
    }

    searchCustomers(query) {
        // 实时搜索客户
        if (query.length >= 2) {
            this.debounceCustomerSearch(query);
        }
    }

    debounceCustomerSearch(query) {
        clearTimeout(this.customerSearchTimeout);
        this.customerSearchTimeout = setTimeout(() => {
            console.log(`Searching customers: ${query}`);
            // 实际项目中这里会调用API搜索
        }, 300);
    }

    filterCustomerList(query) {
        const customerItems = document.querySelectorAll('.customer-item');
        
        customerItems.forEach(item => {
            const name = item.querySelector('.customer-name').textContent;
            const phone = item.querySelector('.customer-phone').textContent;
            
            const matches = !query || 
                name.toLowerCase().includes(query.toLowerCase()) ||
                phone.includes(query);
            
            item.style.display = matches ? 'flex' : 'none';
        });
    }

    selectCustomer(customerId) {
        // 模拟获取客户信息
        const customerData = this.getCustomerData(customerId);
        
        // 更新已选择客户显示
        this.addSelectedCustomer(customerData);
        
        // 关闭选择器
        this.closeCustomerSelector();
        
        // 更新关联表单字段
        this.updateCustomerRelatedFields(customerData);
    }

    getCustomerData(customerId) {
        // 模拟客户数据
        const customers = {
            '101': { id: '101', name: '李大妈', phone: '139****8002', avatar: '李' },
            '102': { id: '102', name: '王先生', phone: '137****8003', avatar: '王' },
            '103': { id: '103', name: '陈阿姨', phone: '138****8004', avatar: '陈' }
        };
        
        return customers[customerId] || {};
    }

    addSelectedCustomer(customer) {
        const container = document.getElementById('selected-customers');
        
        // 检查是否已选择
        if (container.querySelector(`[data-customer-id="${customer.id}"]`)) {
            this.showNotification('客户已经被选择', 'warning');
            return;
        }
        
        const customerElement = document.createElement('div');
        customerElement.className = 'selected-customer';
        customerElement.dataset.customerId = customer.id;
        customerElement.innerHTML = `
            <span class="customer-avatar">${customer.avatar}</span>
            <span class="customer-name">${customer.name}</span>
            <span class="customer-phone">${customer.phone}</span>
            <button type="button" class="remove-btn" onclick="opportunityForm.removeSelectedCustomer('${customer.id}')">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        container.appendChild(customerElement);
        
        // 更新决策分析部分的选项
        this.updateDecisionMakerOptions();
    }

    removeSelectedCustomer(customerId) {
        const element = document.querySelector(`[data-customer-id="${customerId}"]`);
        if (element) {
            element.remove();
            this.updateDecisionMakerOptions();
        }
    }

    updateDecisionMakerOptions() {
        const selectedCustomers = document.querySelectorAll('.selected-customer');
        const selects = [
            'main-decision-maker',
            'decision-influencer',
            'payer'
        ];
        
        selects.forEach(selectId => {
            const select = document.getElementById(selectId);
            if (select) {
                // 保存当前值
                const currentValue = select.value;
                
                // 清除选项（除了默认选项）
                while (select.children.length > 1) {
                    select.removeChild(select.lastChild);
                }
                
                // 添加客户选项
                selectedCustomers.forEach(customer => {
                    const option = document.createElement('option');
                    option.value = customer.dataset.customerId;
                    option.textContent = customer.querySelector('.customer-name').textContent;
                    select.appendChild(option);
                });
                
                // 恢复值
                if (currentValue) {
                    select.value = currentValue;
                }
            }
        });
    }

    updateCustomerRelatedFields(customer) {
        // 根据客户信息更新相关字段的默认值
        // 例如，如果是老客户，可以预填一些信息
    }

    // ==================== 特殊组件处理 ====================
    updateRatingValue(rangeElement) {
        const valueElement = rangeElement.parentNode.querySelector('.rating-value');
        if (valueElement) {
            valueElement.textContent = rangeElement.value;
        }
    }

    toggleCompetitorDetails(show) {
        const detailsElement = document.getElementById('competitor-details');
        if (detailsElement) {
            detailsElement.style.display = show ? 'block' : 'none';
        }
    }

    updateRequirementTags() {
        const selectedTags = [];
        document.querySelectorAll('.tag-checkbox input:checked').forEach(checkbox => {
            selectedTags.push(checkbox.value);
        });
        
        // 可以将选中的标签存储到隐藏字段或直接保存到formData
        this.formData.requirementTags = selectedTags;
    }

    // ==================== 组件初始化 ====================
    initializeComponents() {
        // 初始化日期选择器默认值
        this.initializeDateFields();
        
        // 初始化评分滑块
        this.initializeRatingSliders();
        
        // 初始化提醒设置
        this.initializeReminderSettings();
    }

    initializeDateFields() {
        // 设置预计成交日期默认值（一周后）
        const oneWeekLater = new Date();
        oneWeekLater.setDate(oneWeekLater.getDate() + 7);
        
        const closeDate = document.getElementById('expected-close-date');
        if (closeDate && !closeDate.value) {
            closeDate.value = oneWeekLater.toISOString().split('T')[0];
        }
        
        // 设置首次跟进时间默认值（明天上午10点）
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        tomorrow.setHours(10, 0, 0, 0);
        
        const followupTime = document.getElementById('first-followup-time');
        if (followupTime && !followupTime.value) {
            followupTime.value = tomorrow.toISOString().slice(0, 16);
        }
    }

    initializeRatingSliders() {
        document.querySelectorAll('.factor-range').forEach(range => {
            this.updateRatingValue(range);
        });
    }

    initializeReminderSettings() {
        // 默认选中30分钟提醒
        const defaultReminder = document.querySelector('input[value="30min"]');
        if (defaultReminder) {
            defaultReminder.checked = true;
        }
    }

    // ==================== 表单提交 ====================
    collectFormData() {
        const formData = new FormData(document.getElementById('opportunity-form'));
        const data = {};
        
        // 收集表单数据
        for (const [key, value] of formData.entries()) {
            data[key] = value;
        }
        
        // 收集额外数据
        data.selectedCustomers = Array.from(document.querySelectorAll('.selected-customer'))
            .map(el => el.dataset.customerId);
        
        data.requirementTags = Array.from(document.querySelectorAll('.tag-checkbox input:checked'))
            .map(cb => cb.value);
        
        data.reminderSettings = Array.from(document.querySelectorAll('.reminder-options input:checked'))
            .map(cb => cb.value);
        
        // 收集评分数据
        data.decisionFactors = {};
        document.querySelectorAll('.factor-range').forEach(range => {
            data.decisionFactors[range.id] = range.value;
        });
        
        return data;
    }

    validateAllSteps() {
        let isValid = true;
        const errors = [];
        
        for (let step = 1; step <= this.totalSteps; step++) {
            const stepRules = this.validationRules[`step${step}`];
            if (stepRules) {
                Object.keys(stepRules).forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field && !this.validateField(field, stepRules[fieldId])) {
                        isValid = false;
                        errors.push(`步骤${step}: ${this.getFieldLabel(fieldId)}`);
                    }
                });
            }
        }
        
        if (!isValid) {
            this.showValidationErrors(errors);
        }
        
        return isValid;
    }

    submitForm() {
        // 验证所有步骤
        if (!this.validateAllSteps()) {
            return;
        }
        
        // 收集表单数据
        const formData = this.collectFormData();
        
        // 提交数据
        this.submitOpportunityData(formData);
    }

    submitOpportunityData(data) {
        // 显示加载状态
        this.setSubmitButtonLoading(true);
        
        // 模拟API调用
        console.log('Submitting opportunity data:', data);
        
        setTimeout(() => {
            this.setSubmitButtonLoading(false);
            
            if (this.isEditing) {
                this.showNotification('销售机会已更新', 'success');
            } else {
                this.showNotification('销售机会已创建', 'success');
            }
            
            // 跳转到详情页或列表页
            setTimeout(() => {
                if (this.isEditing) {
                    window.location.href = `opportunity-detail.html?id=${this.opportunityId}`;
                } else {
                    window.location.href = 'opportunity-management.html';
                }
            }, 1500);
            
        }, 2000);
    }

    saveDraft() {
        const formData = this.collectFormData();
        
        this.showNotification('正在保存草稿...', 'info');
        
        // 模拟保存草稿
        setTimeout(() => {
            this.showNotification('草稿已保存', 'success');
        }, 1000);
    }

    setSubmitButtonLoading(isLoading) {
        const submitBtn = document.getElementById('save-opportunity-btn');
        if (submitBtn) {
            if (isLoading) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 正在提交...';
            } else {
                submitBtn.disabled = false;
                submitBtn.innerHTML = this.isEditing ? 
                    '<i class="fas fa-save"></i> 保存修改' : 
                    '<i class="fas fa-check"></i> 创建机会';
            }
        }
    }

    // ==================== 工具方法 ====================
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${this.getNotificationIcon(type)}"></i>
                <span>${message}</span>
            </div>
        `;
        
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${this.getNotificationColor(type)};
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 10000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            max-width: 400px;
            word-wrap: break-word;
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 10);
        
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (document.body.contains(notification)) {
                    document.body.removeChild(notification);
                }
            }, 300);
        }, type === 'error' ? 5000 : 3000);
    }

    getNotificationIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'exclamation-circle',
            warning: 'exclamation-triangle',
            info: 'info-circle'
        };
        return icons[type] || 'info-circle';
    }

    getNotificationColor(type) {
        const colors = {
            success: '#30d158',
            error: '#ff3b30',
            warning: '#ff9500',
            info: '#007AFF'
        };
        return colors[type] || '#007AFF';
    }
}

// ==================== 全局函数 ====================
function closeCustomerSelector() {
    window.opportunityForm.closeCustomerSelector();
}

// ==================== 初始化 ====================
document.addEventListener('DOMContentLoaded', () => {
    window.opportunityForm = new OpportunityForm();
});